#!/bin/bash
set -e
set -u
#
# Run a simple backup on a mysql database
#   then convert to postgresql and restore it.
#

TestName="$(basename "$(pwd)")"
export TestName

JobName=backup-susan-fd
. ./environment
. ${scripts}/functions

. ./environment-postgresql
${scripts}/cleanup
${scripts}/setup

. ./environment-mysql
${scripts}/cleanup
${scripts}/setup

# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data

echo "$conf"/susan-fd.d  >  "$tmp/file-list-python-plugin"

start_test

#enable only mysql
rm -f "${conf}"/susan-dir.d/catalog/postgresql.conf "${conf}"/susan-dir.d/catalog/mysql.conf
cp "${conf}"/susan-dir.d/catalog/mysql.conf.template "${conf}"/susan-dir.d/catalog/mysql.conf

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
label volume=TestVolume001 storage=File pool=Full catalog=mysql
run job=$JobName yes
status director
status client=susan-fd
status storage=File
wait
messages
@$out $tmp/files.mysql
messages
list files jobid=1
END_OF_DATA

run_susan
stop_susan

#enable mysql and postgresql
cp "${conf}"/susan-dir.d/catalog/postgresql.conf.template "${conf}"/susan-dir.d/catalog/postgresql.conf

#do the database copy
"${SUSAN_DBCOPY_BINARY}" -c "${current_test_directory}"/etc/susan mysql postgresql

#enable only postgresql
rm "${conf}"/susan-dir.d/catalog/mysql.conf

cat <<END_OF_DATA >$tmp/bconcmds
@#
@# now do a restore on the postgresql database
@#
@$out $tmp/log2.out
wait
restore client=susan-fd fileset=SelfTest where=$tmp/susan-restores select all done
yes
wait
messages
@$out $tmp/files.postgresql
messages
list files jobid=1
END_OF_DATA

run_susan
check_for_zombie_jobs storage=File client=susan-fd
stop_susan

check_two_logs
check_restore_diff "${BackupDirectory}"

sed -i '/Using Catalog.*/d' "${tmp}"/files.postgresql
sed -i '/Using Catalog.*/d' "${tmp}"/files.mysql

sort "${tmp}"/files.mysql -o "${tmp}"/files.mysql
sort "${tmp}"/files.postgresql -o "${tmp}"/files.postgresql

if ! diff "${tmp}"/files.mysql "${tmp}"/files.postgresql;
then
  estat=1
  echo "differences in \"list files jobid=1\" output!"
fi

end_test
